package com.dps.omc.publish;

import com.dps.omc.enumer.EnumGroupType;
import com.dps.omc.service.*;
import com.dps.omc.task.message.EnumTaskState;
import com.dps.omc.utils.StateConstants;
import com.dps.omc.utils.SysSetting;
import com.dps.common.utils.DateUtils;
import com.dps.omc.model.*;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.*;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by shurrik on 2016/1/7.
 */

@SuppressWarnings("unchecked")
@Service("TaskManager")
public class TaskManager {
    private final static Logger logger = LoggerFactory.getLogger(TaskManager.class);
//    @Autowired
//    private IProducerService producerService;
    @Autowired
    private MsgManager msgManager;
    @Autowired
    private ITaskService taskService;
    @Autowired
    private IAgentService agentService;
    @Autowired
    private ITemplateShellService templateShellService;
    @Autowired
    private ITaskParamService taskParamService;
    @Autowired
    private ITaskNodeService taskNodeService;
    @Autowired
    private IJobPreScriptService jobPreScriptService;
    @Autowired
    private IServerService serverService;
    @Autowired
    private ITelnetServerService telnetServerService;

    public void create(Job job,Agent agent,AgentNode agentNode,JobArtifact jobArtifact,int seq,User lastModified)
    {
        //创建任务
        Task task = taskService.create(job,jobArtifact,agent,agentNode,seq,lastModified);
        //创建任务节点
        taskNodeService.create(job,task,agentNode);
        //创建任务参数
        taskParamService.create(task, jobArtifact,agentNode);
    }

    public void run(Job job,Task task,User lastModified) throws Exception {
//        TemplateShell templateShell = templateShellService.fetch(task.getTemplateId());
//        List<TaskParam> params = taskParamService.findList("taskId", task.getId());
//
//        String shell = this.renderCmd(job,templateShell,params);
        String shell = this.generateCmd(job,task);
        Agent agent = agentService.fetch(task.getAgentId());
        TaskNode taskNode = taskNodeService.findOne("taskId",task.getId());
        if(taskNode.getGroupType().equals(EnumGroupType.SERVER))
        {
            Server server = serverService.fetch(taskNode.getNodeId());
            //发送消息
            msgManager.sendCommandMessageByServer(task,agent,server,shell);
        }
        else if(taskNode.getGroupType().equals(EnumGroupType.TELNET))
        {
            TelnetServer telnetServer = telnetServerService.fetch(taskNode.getNodeId());
            //发送消息
            msgManager.sendCommandMessageByTelnetServer(task,agent,telnetServer,shell);
        }
        else
        {
            //发送消息
            msgManager.sendCommandMessageByDbServer(task,agent,shell);
        }


        //将任务状态置为开始执行
        task.setActualDate(DateUtils.now());
        task.setStartDate(DateUtils.now());
        task.setStatus(EnumTaskState.LOADING);
        taskService.update(task,lastModified);
    }

    public String generateCmd(Job job,Task task) throws Exception
    {
        TemplateShell templateShell = templateShellService.fetch(task.getTemplateId());
        List<TaskParam> params = taskParamService.findList("taskId", task.getId());

        String shell = this.renderCmd(job,templateShell,params);
        return shell;
    }

    private String renderCmd(Job job,TemplateShell templateShell,List<TaskParam> params) throws Exception {

        String preScript = this.renderPreScript(job);
        String shell = this.renderTemplateShell(templateShell,params);
        String cmd = preScript+shell;
        logger.info(cmd);
        return cmd;
    }

    private String renderPreScript(Job job) {

        String script = "";
        List<JobPreScript> jobPreScripts = jobPreScriptService.findList("jobId",job.getId());
        StringBuffer sb = new StringBuffer();
        String fileHost = SysSetting.getValue(StateConstants.FILE_HOST);
        for(JobPreScript jobPreScript:jobPreScripts)
        {
            sb.append("wget "+fileHost+"/file/"+jobPreScript.getArtifactId()+" -O "+jobPreScript.getStorePath()+"/"+jobPreScript.getStoreName()+" 2>/dev/null;");
        }
        return sb.toString();
    }

    private String renderTemplateShell(TemplateShell templateShell,List<TaskParam> params) throws Exception {

        Configuration cfg = new Configuration();
        StringTemplateLoader stringLoader = new StringTemplateLoader();
        String templateContent=templateShell.getContent();
        stringLoader.putTemplate("myShell",templateContent);

        cfg.setTemplateLoader(stringLoader);

        Template template = cfg.getTemplate("myShell","utf-8");
        Map<String,Object> model = new HashMap();
        for(TaskParam param:params)
        {
            model.put(param.getTplKey(),param.getTplVal());
        }

        StringWriter writer = new StringWriter();
        template.process(model, writer);
        return writer.toString();
    }


//    private String renderCmd(TemplateShell templateShell,List<TaskParam> params) throws Exception {
//
//        Configuration cfg = new Configuration();
//        StringTemplateLoader stringLoader = new StringTemplateLoader();
//        String templateContent=templateShell.getContent();
//        stringLoader.putTemplate("myShell",templateContent);
//
//        cfg.setTemplateLoader(stringLoader);
//
//        Template template = cfg.getTemplate("myShell","utf-8");
//        Map<String,Object> model = new HashMap();
//        for(TaskParam param:params)
//        {
//            model.put(param.getTplKey(),param.getTplVal());
//        }
//
//        StringWriter writer = new StringWriter();
//        template.process(model, writer);
//        return writer.toString();
//    }
}
